<?php

	require_once("../../../includes/config.inc.php");
	
	$titulo = str_replace("'", "&quot;", $_POST["titulo"]);
	$titulo = str_replace('"', "&quot;", $titulo);
	
	if($_GET['action'] == "insert"){
	
		mysql_query("INSERT INTO fotos (titulo, data) VALUES ('".$titulo."', NOW())");
		$last_id = mysql_fetch_row(mysql_query("SELECT LAST_INSERT_ID()"));
		$diretorio = $last_id[0];
		
		$dir = "../../../";
		$provisorio = "admin/provisoria";
		
		if(is_dir($dir."/".$provisorio)){
			rename($dir."/".$provisorio, $dir."/images/fotos/".$diretorio);
		}
		
		header("location: ../../index.php?option=into&view=fotos");
	
	}else if($_GET['action'] == "update"){
		
		mysql_query("UPDATE fotos SET titulo = '".$titulo."' WHERE idfotos = ".$_GET['itemId']);
		
		header("location: ../../index.php?option=into&view=fotos");
	
	}else if($_GET['action'] == "delete"){
		
		$excluir = $_POST['excluir'];
		for($i=0; $i<count($excluir); $i++){
								  
			$arquivo = $excluir[$i];
			$targetPath = "../../../images/fotos/".$arquivo."/";
			if(is_dir($targetPath)){
				$dh = opendir($targetPath);
				while($file = readdir($dh)){
					if($file != "." && $file != ".."){
						$fullpath = $targetPath.$file;
						if(!is_dir($fullpath)){
							unlink($fullpath);
						}
					}	
				}
				closedir($dh);	
				rmdir($targetPath);
			}
			
			mysql_query("DELETE FROM fotos WHERE idfotos = ".$excluir[$i]) or die (mysql_error());
		
		}
		header("location: ../../index.php?option=into&view=fotos");
		
	}else if($_GET['action'] == "config"){
		
		$atualizar = $_POST['excluir'];
		if(!empty($atualizar)){
			for($i=0; $i<1; $i++){
				
				header("location: ../../index.php?option=into&view=fotos&action=update&itemId=".$atualizar[$i]);
			
			}
		}else{
			header("location: ../../index.php?option=into&view=fotos");	
		}
	
	}else{
		
		echo "<h1>Houve um erro inesperado!</h1>";
	
	}
	
	

?>